package io.github.kuafucv.zero.log.spring.boot.starter.configuration;

import io.github.kuafucv.zero.log.core.slow.request.filter.SlowRequestFilter;
import io.github.kuafucv.zero.log.core.slow.request.pattern.SlowRequestThresholdFactory;
import io.github.kuafucv.zero.log.spring.boot.starter.properties.ZeroLogProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Collections;

@ConditionalOnProperty(name = "zero.log.slow-request.enabled",havingValue = "true",matchIfMissing = true)
@Configuration
@EnableConfigurationProperties(ZeroLogProperties.class)
public class ZeroLogAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public SlowRequestThresholdFactory slowRequestThresholdFactory() {
        return new DefaultSlowRequestThresholdFactory();
    }

    @Bean
    public FilterRegistrationBean<SlowRequestFilter> slowRequestFilterFilterRegistrationBean(ZeroLogProperties zeroLogProperties,SlowRequestThresholdFactory slowRequestThresholdFactory) {
        FilterRegistrationBean<SlowRequestFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new SlowRequestFilter(zeroLogProperties.getSlowRequest().getDefaultTimeThreshold(), slowRequestThresholdFactory));
        bean.setOrder(Integer.MIN_VALUE);
        bean.setUrlPatterns(Collections.singletonList("/*"));
        return bean;
    }

}
